import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from "primeng/dynamicdialog";
import {AuthService} from "../../../../services/auth.service";
import {AlertService} from "../../../../services/alert.service";
import {Dept} from "../../../../model/auth/Dept";
import {StringUtils} from "../../../../services/StringUtils";

@Component({
  selector: 'app-deptedit',
  templateUrl: './deptedit.component.html',
  styleUrl: './deptedit.component.css'
})
export class DepteditComponent implements OnInit, OnDestroy {
  id:string;
  private authservice:AuthService=inject(AuthService);
  private alertservice:AlertService=inject(AlertService);
  d:Dept;


  constructor(public ref: DynamicDialogRef, public config: DynamicDialogConfig) {
    this.d=new Dept();

  }

  ngOnInit(): void {

    //console.dir(this.ref.data);
    console.dir(this.config.data);


    if(this.config.data.optype=='add'){
      this.d.pid=this.config.data.pid
    }
    else if(this.config.data.optype=='update'){
      this.id=this.config.data.id;
      this.getDeptById();
    }

  }

  ngOnDestroy(): void {

  }

  confirm(){

    if(StringUtils.isEmpty(this.d.name)){
      this.alertservice.showWarn('部门名称不能为空')
    }
    else if(this.d.sort==null){
      this.alertservice.showWarn('排序号不能为空');
    }
    else {
      this.save();
    }

  }

  save(){
    this.authservice.saveDept(this.d)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.alertservice.showSuccess('保存成功');
          this.ref.close('ok');
        }
        else {
          this.alertservice.showError('保存失败，请刷新后重试');
          this.ref.close('error');
        }
      })
  }


  getDeptById(){
    this.authservice.getDeptById(this.id)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.d=new Dept();
          this.d=data.obj;
        }
        else {
          this.alertservice.showError('参数错误，请刷新后重试');
          this.ref.close('parmerror');
        }
      })
  }

}
